from django.http import HttpResponse
from django.utils.deprecation import MiddlewareMixin
from jwt import ExpiredSignatureError, InvalidTokenError, PyJWTError
from rest_framework_jwt.settings import api_settings


class JwtAuthenticationMiddleware(MiddlewareMixin):

    # 在请求之前进行处理
    def process_request(self, request):
        white_list = ["/admin/login", "/admin/logout", "/user/blog", "/article/blog", "/category/blog", "/tag/blog", "/message/blog", "/webinfo/blog", "/swagger/", "/redoc/"]  # 请求白名单
        path = request.path
        print(path)

        # 检查路径是否包含白名单中的字段
        if not any(white_path in path for white_path in white_list) and not path.startswith("/media"):
            print("要进行token验证")
            token = request.META.get("HTTP_AUTHORIZATION")
            # 去除 token 前面的 "Bearer " 部分
            if token and token.startswith("Bearer "):
                token = token[7:]
            print(token)
            try:
                jwt_decode_handle = api_settings.JWT_DECODE_HANDLER
                jwt_decode_handle(token)
            except ExpiredSignatureError:
                return HttpResponse('Token过期，请重新登录！')
            except InvalidTokenError:
                return HttpResponse('Token验证失败！')
            except PyJWTError:
                return HttpResponse('Token验证异常！')
        else:
            print("不需要token验证")
            return None